package com.zenith.gateway.service;

import com.zenith.common.result.Result;
import com.zenith.gateway.feign.UserFeignClient;
import com.zenith.gateway.po.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 自定义OAuth2用户详情服务
 * 用于加载用户信息进行认证
 */
@Slf4j
@Component
public class CustomOAuth2UserDetailsService implements UserDetailsService {

    @Autowired
    @Lazy
    private UserFeignClient userFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<UserDTO> result = userFeignClient.getUserByUsername(username);

        if (result == null || result.getCode() != 200 || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserDTO user = result.getData();

        return User.withUsername(user.getUsername())
                .password(user.getPassword())
                .authorities(user.getRole())
                .accountExpired(false)
                .accountLocked(false)
                .credentialsExpired(false)
                .disabled(false)
                .build();
    }
}